package com.jy.modules.cims.component.funds.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.CimsFundsConstant;
import com.jy.modules.cims.common.open.api.enums.EntryResponseEnum;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.component.api.IJieYueSend;
import com.jy.modules.cims.component.common.service.TCMmFundsRiskactService;
import com.jy.modules.cims.data.common.dao.TCMmFundsrepayStreamDao;
import com.jy.modules.cims.data.common.dto.TCMmFundsRiskactDTO;
import com.jy.modules.cims.data.dao.DiscountInquiryDao;
import com.jy.modules.cims.data.dao.FundsBorrowerBankactDao;
import com.jy.modules.cims.data.dao.FundsRepayStreamDao;
import com.jy.modules.cims.data.dao.FundsRiskactDao;
import com.jy.modules.cims.data.dto.fundsbalance.FundsBorrowerBankactDTO;
import com.jy.modules.cims.data.dto.fundsbalance.FundsDisCountDTO;
import com.jy.modules.cims.data.dto.fundsbalance.FundsRepayStreamDTO;
import com.jy.modules.cims.data.dto.fundsbalance.FundsRiskactDTO;
import com.jy.modules.cims.data.interact.api.JieYueResponseData;
import com.jy.modules.cims.data.interact.api.request.funds.RequestRepaymentFundsNoticeDTO;
import com.jy.modules.cims.data.interact.api.request.funds.RequestTransferFundsAccountdtorepayDTO;
import com.jy.modules.cims.data.interact.api.response.funds.ResponseRepaymentFundsNoticeDTO;
import com.jy.modules.cims.data.interact.api.response.funds.ResponseTransferFundsAccountdtorepayDTO;
import com.jy.modules.cims.data.interact.funds.RequestFundsRiskDTO;
import com.jy.modules.cims.data.interact.funds.ResponseFundsRiskDTO;
import com.jy.modules.cims.data.interact.funds.response.Response4051ResultDTO;
import com.jy.modules.cims.interact.CIRCreditPoolIFImpl;
import com.jy.modules.platform.sysconfig.service.SysConfigService;


@Service("com.jy.modules.cims.component.funds.service.impl.FundRepayAccountOutImpl")
public class FundsRepayAccountOutImpl {


	private static Logger logger = LoggerFactory.getLogger(FundsRepayAccountOutImpl.class);
	
	public static Map<String, String> mapRisk = new LinkedHashMap<String, String>();
	static {
		mapRisk.clear();
		mapRisk.put("1", CimsConstant.FUNDS_RISK_STATUS_00);
		mapRisk.put("2", CimsConstant.FUNDS_RISK_STATUS_01);
	}
	

	@Autowired
	public FundsRepayStreamDao fundsRepayStreamDao;
	
	@Autowired
	TCMmFundsrepayStreamDao tCMmFundsrepayStreamDao;
	
	@Autowired
	FundsRiskactDao fundsRiskactDao;

	@Autowired
	FundsBorrowerBankactDao fundsBorrowerBankactDao;
	
	@Autowired
	DiscountInquiryDao discountInquiryDao;
	
	@Autowired
	@Qualifier("jieYueSendService")
	private IJieYueSend jieYueSend;
	
	@Autowired
	@Qualifier("com.jy.modules.platform.sysconfig.service.SysConfigService")
	private SysConfigService sysConfigService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CIRCreditPoolIFImpl")
	private CIRCreditPoolIFImpl creditPoolIFImpl;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmFundsRiskactService")
	private TCMmFundsRiskactService fundsRiskactService;
	
	
	/**
	 * 月还划口（二期）
	 * @author zhangmi
	 * @date  2017年4月25日
	 */
	public void repayPayOut(){
		
		/**
		 * <1> 查询需要划口的合同信息
		 * <2> 调用向上划口借口
		 * <3> finally 修改备注，划口
		 */
		List<FundsRepayStreamDTO> list= fundsRepayStreamDao.getFundsrepayStreamIsNotDeal(SearchParamUtil.getSearchParam());
		for (FundsRepayStreamDTO fundsRepayStreamDTO : list) {
			
			
			try {
				String contractNo = fundsRepayStreamDTO.getContractno();
				String cooperorgCode = fundsRepayStreamDTO.getCooperorgCode();
				RequestTransferFundsAccountdtorepayDTO requestContent = new RequestTransferFundsAccountdtorepayDTO();
				
				
				JieYueResponseData responseData = jieYueSend.transferFundsAccountdtorepay("XS", requestContent);
				if(responseData!=null){
					if(EntryResponseEnum.SUCESS21001.getCode().equals(responseData.getRetCode())){
//						ResponseTransferFundsAccountdtorepayDTO ddd = (ResponseTransferFundsAccountdtorepayDTO)responseData.getData();
						
						
						
					}else{
						logger.info("合作机构【{}】，划口接口异常编码【{}】，异常描述【{}】，合同号【{}】！",cooperorgCode,responseData.getRetCode(),responseData.getMessage(),contractNo);
					}
				}else{
					logger.info("合作机构【{}】，划口接口异常，返回数据为空！",cooperorgCode);
				}
			} catch (Exception e) {
				
				logger.error("合同号{},划口失败:{}");
			}finally{
				
				//修改备注，已划口
				
			}
		}
	}
	
	/**
	 * 风险金入库
	 * <1>:调用主数据接口 (获取主数据配配置的天数：15)
	 * <2>:调用志强接口：获取今天前15天的，需要垫付的金额。（15以参数穿过去）
	 * <3>:插入入库
	 * <4>:调用向上：风险金垫付接口
	 * <5>:修改状态：
	 * 
	 * @author zhangmi
	 * @throws Exception 
	 * @date  2017年4月27日
	 */
	public void insertRisk() throws Exception{
		
		//<1>主数据获取参数

		String cCodes = sysConfigService.queryValueByCode(CimsFundsConstant.FUND_ZJCG_CCODE);
		String DisMentRiskDay = sysConfigService.queryValueByCode(CimsFundsConstant.FUND_ZJCG_RISK_DAY);
		
		String [] aryCodes = cCodes.split(",");
		for (String cooperorgCode : aryCodes) {
			RequestFundsRiskDTO req =new RequestFundsRiskDTO();
			req.setBusiType("1");
			req.setCooperorgCode(cooperorgCode.trim());
			req.setmCount(DisMentRiskDay);
			ResponseFundsRiskDTO  rltResponst= creditPoolIFImpl.getRiskInsertByCore(req);
			
			if(rltResponst.isSuccess()){
				//<3>数据入库
				TCMmFundsRiskactDTO tcmmRiskactDTO = null;
				for (Response4051ResultDTO response4051ResultDTO : rltResponst.getRiskList()) {
					try {
						tcmmRiskactDTO = new TCMmFundsRiskactDTO();
//						tcmmRiskactDTO = TCMmFundsRiskactDTO.StaticToCopyBeanInsert(response4051ResultDTO, tcmmRiskactDTO);
						tcmmRiskactDTO.setCooperorgCode(response4051ResultDTO.getcCode());//机构
						tcmmRiskactDTO.setContractno(response4051ResultDTO.getCreditId());//债权
						tcmmRiskactDTO.setDispayDate(response4051ResultDTO.getAdvanceDate());//垫付日期
						tcmmRiskactDTO.setBillDate(response4051ResultDTO.getBizDate());//逾期日期
						tcmmRiskactDTO.setRiskStatus(CimsConstant.FUNDS_RISK_STATUS_00);//未垫付
						tcmmRiskactDTO.setValidateState("1");//
						tcmmRiskactDTO.setCreateTime(new Timestamp(System.currentTimeMillis()));
						tcmmRiskactDTO.setModifyTime(new Timestamp(System.currentTimeMillis()));
						fundsRiskactService.insertTCMmFundsRiskact(tcmmRiskactDTO);
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						logger.error("风险金入库失败！合同号{},异常",response4051ResultDTO.getCreditId(),e.getMessage());
					}
					
				}
			}else{
				logger.error("风险金入库：核心接口返回数据失败！！");
			}
		}
		//<2>调用核心接口，数据入库
		
	}
	
	
	/**
	 * 风险金垫付
	 * <1>:提前有个定时任务，刷那些需要垫付的合同号。
	 * <2>:查询所有需要垫付的合同号list
	 * <3>:调用向上的接口：垫付
	 * <4>:修改状态为已经垫付
	 * 
	 * @author zhangmi
	 * @throws Exception 
	 * @date  2017年4月25日
	 */
	public void transferDisBurseMent() throws Exception{
		
		String cCodes = sysConfigService.queryValueByCode(CimsFundsConstant.FUND_ZJCG_RISK_CCODE);
		String [] aryCodes = cCodes.split(",");
		for (String cCode : aryCodes) {
			//<1>:查询所有需要垫付的合同号list
			TCMmFundsRiskactDTO tcmmFundsRiskactDTO = new TCMmFundsRiskactDTO();
			tcmmFundsRiskactDTO.setCooperorgCode(cCode);
			tcmmFundsRiskactDTO.setRiskStatus(CimsConstant.FUNDS_RISK_STATUS_00);
			List<TCMmFundsRiskactDTO> riskList = fundsRiskactService.searchTCMmFundsRiskact(SearchParamUtil.getSearchParam(tcmmFundsRiskactDTO));
			FundsRiskactDTO uptDto = null;
			
			//<2>：风险金垫付
			for (TCMmFundsRiskactDTO fundsRiskactDTO : riskList) {
				try {
					String contractNo = fundsRiskactDTO.getContractno();
					String cooperorgCode = fundsRiskactDTO.getCooperorgCode();
					RequestTransferFundsAccountdtorepayDTO requestContent = new RequestTransferFundsAccountdtorepayDTO();
					//电子账户信息
					FundsBorrowerBankactDTO fundsBorrower = getUserIdAct(contractNo);
					//获取代偿账户
					requestContent.setBankcode(CimsFundsConstant.fundsActCfg.get(cooperorgCode).get(CimsFundsConstant.FUND_DC_BANKCODE));//
					requestContent.setBankname(CimsFundsConstant.fundsActCfg.get(cooperorgCode).get(CimsFundsConstant.FUND_DC_BANKNAME));
					requestContent.setCardnbr(CimsFundsConstant.fundsActCfg.get(cooperorgCode).get(CimsFundsConstant.FUND_DC_BANKCARD));
					requestContent.setTransamt(fundsRiskactDTO.getRiskAccount());
					requestContent.setUserid(fundsBorrower.getUserid());
					
					//<3>:调用向上的接口：垫付
					JieYueResponseData responseData = jieYueSend.transferFundsAccountdtorepay(cooperorgCode, requestContent);
					if(responseData!=null){
						if(EntryResponseEnum.SUCESS21001.getCode().equals(responseData.getRetCode())){
							ResponseTransferFundsAccountdtorepayDTO response = (ResponseTransferFundsAccountdtorepayDTO)responseData.getData();
							if(CimsConstant.JIEYU_RET_CODE_SUC.equals(response.getResult())){
								//<4>:修改状态为已经垫付
								uptDto = new FundsRiskactDTO();
								uptDto.setId(fundsRiskactDTO.getId());
								uptDto.setRiskStatus(CimsConstant.FUNDS_RISK_STATUS_01);//已垫付
								fundsRiskactDao.updateRiskStatus(SearchParamUtil.getSearchParam(uptDto));
							}else{
								logger.error("合作机构【{}】，风险金垫付接口异常【{}】，异常描述【{}】，合同号【{}】！",cooperorgCode,response.getResult(),response.getMessage(),contractNo);
							}
						}else{
							logger.error("合作机构【{}】，风险金垫付接口异常【{}】，异常描述【{}】，合同号【{}】！",cooperorgCode,responseData.getRetCode(),responseData.getMessage(),contractNo);
						}
					}else{
						logger.error("合作机构【{}】，风险金垫付接口异常，返回数据为空！",cooperorgCode);
					}
				
				
				}catch (Exception e) {
					
					logger.error("合同号{},划口失败:{}");
				}finally{
					//修改备注，已划口
					//this.updateIsDealed(fundsRepayStreamDTO.getId(), CimsConstant.FUNDS_IS_DEAL_00, "已垫付");
				}
			}
		}
		
		
		
		
	}
	
	/**
	 * 贴息
	 * <1>:贴息合同号查询出List   :结算计划新增一个贴息状态:01：老数据，02：需要贴息,03：已经贴息
	 * <2>:查询:02需要贴息的数据List
	 * <3>:循环遍历：调用贴息金额
	 * <4>:调用向上贴息
	 * <5>:修改贴息状态
	 * 
	 * @author zhangmi
	 * @date  2017年4月27日
	 */
	public void transferDisCount(){
		
		//<2>:查询所有需要垫付的合同号list
		String cCodes = sysConfigService.queryValueByCode(CimsFundsConstant.FUND_ZJCG_DICT_CCODE);
		String [] aryCodes = cCodes.split(",");
		for (String cCode : aryCodes) {
			//<1>:根据合作机构  ，昨天日期，查询贴息
			FundsDisCountDTO searchDto = new FundsDisCountDTO();
			searchDto.setCooperorgCode(cCode);//合作机构
			searchDto.setStartDate(DateTimeUtils.GetYesterDay());//设置昨天的日期
			List<FundsDisCountDTO> list= discountInquiryDao.searchDiscount(SearchParamUtil.getSearchParam(searchDto));
			
			FundsRepayStreamDTO uptDto = null;
			for (FundsDisCountDTO fundsDisCountDTO : list) {
				
				///如果垫付金额大于0
				if(fundsDisCountDTO.getDisCount().compareTo(BigDecimal.ZERO)>0){
					try {
						String contractNo = fundsDisCountDTO.getTransferId();
						String cooperorgCode = fundsDisCountDTO.getCooperorgCode();
						RequestTransferFundsAccountdtorepayDTO requestContent = new RequestTransferFundsAccountdtorepayDTO();
		
						FundsBorrowerBankactDTO fundsBorrower = getUserIdAct(contractNo);
						//获取代偿账户
						requestContent.setBankcode(CimsFundsConstant.fundsActCfg.get(cooperorgCode).get(CimsFundsConstant.FUND_DC_BANKCODE));//
						requestContent.setBankname(CimsFundsConstant.fundsActCfg.get(cooperorgCode).get(CimsFundsConstant.FUND_DC_BANKNAME));
						requestContent.setCardnbr(CimsFundsConstant.fundsActCfg.get(cooperorgCode).get(CimsFundsConstant.FUND_DC_BANKCARD));
						requestContent.setTransamt(fundsDisCountDTO.getDisCount());
						requestContent.setUserid(fundsBorrower.getUserid());
						
						//<3>:调用向上的接口：垫付
						JieYueResponseData responseData = jieYueSend.transferFundsAccountdtorepay(cooperorgCode, requestContent);
						if(responseData!=null){
							if(EntryResponseEnum.SUCESS21001.getCode().equals(responseData.getRetCode())){
								ResponseTransferFundsAccountdtorepayDTO response = (ResponseTransferFundsAccountdtorepayDTO)responseData.getData();
								if(CimsConstant.JIEYU_RET_CODE_SUC.equals(response.getResult())){
									//还款通知
									RequestRepaymentFundsNoticeDTO repayContent = new RequestRepaymentFundsNoticeDTO();
									JieYueResponseData responseRepayData = jieYueSend.repaymentFundsNotice(cooperorgCode, repayContent);
									if(responseRepayData!=null){
										if(EntryResponseEnum.SUCESS21001.getCode().equals(responseRepayData.getRetCode())){
											ResponseRepaymentFundsNoticeDTO responseRepay = (ResponseRepaymentFundsNoticeDTO)responseRepayData.getData();
											if(CimsConstant.JIEYU_RET_CODE_SUC.equals(responseRepay.getResult())){
												logger.info("合作机构【{}】，合同号【{}】，贴息还款通知完毕！",cooperorgCode,contractNo);
											}
										}else{
											logger.info("合作机构【{}】，合同号【{}】，贴息还款通知异常！",cooperorgCode,contractNo,responseRepayData.getMessage());
										}
									}else{
										logger.info("合作机构【{}】，合同号【{}】，贴息还款通知接口报文为空",cooperorgCode,contractNo);
									}
									//<4>:修改状态为已经垫付
									uptDto = new FundsRepayStreamDTO();
									uptDto.setContractno(contractNo);
									fundsRepayStreamDao.updateRiskStatus(SearchParamUtil.getSearchParam(uptDto));
									this.insertIsDisCount(fundsDisCountDTO.getTransferId(), fundsDisCountDTO.getDisCount(), "贴息成功,并通知完毕！");
								}else{
									logger.info("合作机构【{}】，贴息接口异常【{}】，异常描述【{}】，合同号【{}】！",cooperorgCode,response.getResult(),response.getMessage(),contractNo);
								}
							}else{
								logger.info("合作机构【{}】，贴息接口异常【{}】，异常描述【{}】，合同号【{}】！",cooperorgCode,responseData.getRetCode(),responseData.getMessage(),contractNo);
							}
						}else{
							logger.info("合作机构【{}】，贴息接口异常，返回数据为空！",cooperorgCode);
						}
					}catch (Exception e) {
						logger.error("贴息失败，合同号{},贴息失败:{}",fundsDisCountDTO.getTransferId(),e.getMessage());
						this.insertIsDisCount(fundsDisCountDTO.getTransferId(), fundsDisCountDTO.getDisCount(), "贴息失败！");
					}finally{
						//修改备注，已处理
					}
				
				}else{
					logger.error("贴息金额为空！不需要贴息！！合同号：{}",fundsDisCountDTO.getCreditCode());
					this.insertIsDisCount(fundsDisCountDTO.getTransferId(), fundsDisCountDTO.getDisCount(), "贴息金额小于零！");
				}
			}
		}
		
		
	}
	
	
	/**
	 * 修改备注，修改处理状态
	 * @author zhangmi
	 * @date  2017年4月28日
	 * @param id
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 5)
	public void updateIsDealed(final Long id,final String isDeal,final String statusMsg){
		FundsRepayStreamDTO uptDto = new FundsRepayStreamDTO();
		uptDto.setIsDeal(isDeal);
		uptDto.setId(id);
		uptDto.setStatusMsg(statusMsg);
		fundsRepayStreamDao.updateIsDealMsg(SearchParamUtil.getSearchParam(uptDto));
	}
	
	
	/**
	 * 贴息--流水记录
	 * @author zhangmi
	 * @date  2017年5月9日
	 * @param contractNo
	 * @param disCount
	 * @param statusMsg
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 5)
	public void insertIsDisCount(final String contractNo,final BigDecimal disCount,final String statusMsg){
		FundsRepayStreamDTO uptDto = new FundsRepayStreamDTO();
		uptDto.setIsDeal(CimsConstant.FUNDS_IS_DEAL_00);
		uptDto.setContractno(contractNo);
		uptDto.setRepayDiscount(disCount);
		uptDto.setStatusMsg(statusMsg);
		uptDto.setRepayStatus(CimsConstant.FUNDS_REPAY_STATUS_03);//已贴息
		uptDto.setRepayType(CimsConstant.FUNDS_REPAY_TYPE_04);//贴息
		uptDto.setBillDate(DateTimeUtils.GetYesterDay());
		uptDto.setRepayDate(new Date());
		fundsRepayStreamDao.insertDisCountIsDealMsg(SearchParamUtil.getSearchParam(uptDto));
	}
	
	/**
	 * 根据合同号，获取用户电子账户信息
	 * @author zhangmi
	 * @date  2017年5月9日
	 * @param contractNo
	 * @return
	 */
	public FundsBorrowerBankactDTO getUserIdAct(String contractNo){
		FundsBorrowerBankactDTO fundsBorrower = new FundsBorrowerBankactDTO();
		fundsBorrower.setContractNo(contractNo);
		List<FundsBorrowerBankactDTO> list = fundsBorrowerBankactDao.searchFundsBorrowerBankact(SearchParamUtil.getSearchParam(fundsBorrower));
		if(CollectionsUtils.isNotEmpty(list)){
			list.get(0);
		}
		return null;
	}
}
